package com.sc;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author sc
 * Created on  2017/12/15
 * 多Reactor模式，Netty中使用的Reactor模式，主Reactor负责监控所有连接请求，多个子Reactor负责监控并处理读写请求
 * 减轻了主Reactor的压力，降低了延迟
 */
public class MultiReactor {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8080));
        ssc.register(selector, SelectionKey.OP_ACCEPT);

        int coreNum = Runtime.getRuntime().availableProcessors();
        Processor[] processors = new Processor[coreNum];
        for(int i=0;i<processors.length;i++){
            processors[i] = new Processor();
        }
        int index = 0;
        while (selector.select()>0){
            Set<SelectionKey> keySet = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keySet.iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();
                if(key.isAcceptable()){
                    ServerSocketChannel accept = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel = accept.accept();
                    socketChannel.configureBlocking(false);
                    Processor processor = processors[(index++)%coreNum];
                    processor.addChannel(socketChannel);
                    processor.wakeUp();
                }
            }
        }
    }


    public static class Processor{

        private static final ExecutorService service = Executors.newFixedThreadPool(2*Runtime.getRuntime().availableProcessors());
        private Selector selector;

        Processor() throws IOException {
            this.selector = SelectorProvider.provider().openSelector();
            start();
        }

        public void addChannel(SocketChannel socketChannel) throws ClosedChannelException {
            socketChannel.register(this.selector,SelectionKey.OP_READ);
        }

        public void wakeUp(){
            this.selector.wakeup();
        }

        public void start(){
            service.submit(()->{
                while(true){
                    if(selector.select(500)<=0){
                        continue;
                    }
                    Set<SelectionKey> keys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = keys.iterator();
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if(key.isReadable()){
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            SocketChannel channel = (SocketChannel) key.channel();
                            int count = channel.read(buffer);
                            if(count<0){
                                channel.close();
                                key.cancel();
                                continue;
                            } else  if(count==0){
                                continue;
                            }else{
                                System.out.println("waiting");
                            }
                        }
                    }
                }

            });
        }
    }
}
